package com.ctshk.rpc.scenic.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.UuidUtils;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ctshk.common.constant.ErrCode;
import com.ctshk.common.constant.RedisConstants;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.MD5Util;
import com.ctshk.common.utils.RSAUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.scenic.dto.AirshowDistributorSettingDTO;
import com.ctshk.rpc.scenic.entity.AirshowDistributorSetting;
import com.ctshk.rpc.scenic.mapper.AirshowDistributorSettingMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.rpc.scenic.req.AirshowDistributorLoginReq;
import com.ctshk.rpc.scenic.req.AirshowDistributorSettingAddReq;
import com.ctshk.rpc.scenic.req.AirshowDistributorSettingReq;
import com.ctshk.rpc.scenic.service.IAirshowDistributorSettingService;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.logging.log4j.util.Strings;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 谢诗宏
 * @since 2021-06-10
 */
@DubboService
public class AirshowDistributorSettingServiceImpl extends ServiceImpl<AirshowDistributorSettingMapper, AirshowDistributorSetting> implements IAirshowDistributorSettingService {

    @Autowired
    private AirshowDistributorSettingMapper airshowDistributorSettingMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Result getAllDistributorList() {

        QueryWrapper<AirshowDistributorSetting> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete",0);
        queryWrapper.eq("is_enable",1);
        List<AirshowDistributorSetting> airshowDistributorSettings = airshowDistributorSettingMapper.selectList(queryWrapper);

        return Result.success(airshowDistributorSettings);
    }

    @Override
    public Result updateDistributorSetting(AirshowDistributorSettingReq airshowDistributorSettingReq) {

        AirshowDistributorSetting airshowDistributorSetting = EntityUtil.copy(airshowDistributorSettingReq, AirshowDistributorSetting.class);

        int i = airshowDistributorSettingMapper.updateById(airshowDistributorSetting);

        if(i > 0)
            return Result.success();

        throw new BusinessException(SystemError.SYS_437);
    }

    @Override
    public Result addDistributor(AirshowDistributorSettingAddReq airshowDistributorSettingAddReq) {

        if(StringUtils.isBlank(airshowDistributorSettingAddReq.getAgentName())){
            throw new BusinessException(SystemError.SYS_409,"分销商名称不能为空");
        }

        if(StringUtils.isBlank(airshowDistributorSettingAddReq.getMobile())){
            throw new BusinessException(SystemError.SYS_409,"手机号不能为空");
        }

        QueryWrapper<AirshowDistributorSetting> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile",airshowDistributorSettingAddReq.getMobile());
        queryWrapper.eq("is_delete",0);

        AirshowDistributorSetting getByMobile = airshowDistributorSettingMapper.selectOne(queryWrapper);

        if(getByMobile != null){
            throw new BusinessException(SystemError.SYS_430,"手机号已存在");
        }

        AirshowDistributorSetting airshowDistributorSetting = EntityUtil.copy(airshowDistributorSettingAddReq, AirshowDistributorSetting.class);

        long id = SnowflakeIdWorker.nextId();
        airshowDistributorSetting.setId(id);

        String pwd = String.valueOf((int)((Math.random()*9+1)*100000));

        String appSecret = UuidUtils.generateUuid().replace("-", "");

        airshowDistributorSetting.setIsDelete(0);
        airshowDistributorSetting.setIsEnable(1);
        airshowDistributorSetting.setNormalPrice(new BigDecimal(0));
        airshowDistributorSetting.setDiscountPrice(new BigDecimal(0));
        airshowDistributorSetting.setTotalAmount(new BigDecimal(0));
        airshowDistributorSetting.setBalance(new BigDecimal(0));
        airshowDistributorSetting.setRefundServiceCharge(new BigDecimal(0));
        airshowDistributorSetting.setPwd(MD5Util.stringMd5(pwd));
        airshowDistributorSetting.setAppSecret(appSecret);

        int insert = airshowDistributorSettingMapper.insert(airshowDistributorSetting);

        if(insert > 0){

            Map map = new HashMap<>();
            map.put("mobile",airshowDistributorSettingAddReq.getMobile());
            map.put("pwd",pwd);
            map.put("appKey",id);
            map.put("appSecret",appSecret);

            return Result.success(map);
        }

        throw new BusinessException(SystemError.SYS_437);
    }

    @Override
    public Result<AirshowDistributorSettingDTO> getDistributorById(Long id) {

        AirshowDistributorSetting airshowDistributorSetting = airshowDistributorSettingMapper.selectById(id);

        AirshowDistributorSettingDTO copy = EntityUtil.copy(airshowDistributorSetting, AirshowDistributorSettingDTO.class);

        return Result.success(copy);
    }

    @Override
    public Result getDistributorBalanceById(Long id) {

        AirshowDistributorSetting airshowDistributorSetting = airshowDistributorSettingMapper.selectById(id);

        Map map = new HashMap();
        map.put("balance",airshowDistributorSetting.getBalance());

        return Result.success(map);
    }

    @Override
    public Result distributorLogin(AirshowDistributorLoginReq airshowDistributorLoginReq) {

        if(StringUtils.isBlank(airshowDistributorLoginReq.getMobile())){
            throw new BusinessException(SystemError.SYS_428,"手机号");
        }

        if(StringUtils.isBlank(airshowDistributorLoginReq.getPwd())){
            throw new BusinessException(SystemError.SYS_428,"密码");
        }

        QueryWrapper<AirshowDistributorSetting> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("mobile",airshowDistributorLoginReq.getMobile());
        queryWrapper.eq("is_enable",1);
        queryWrapper.eq("is_delete",0);
        queryWrapper.eq("pwd",MD5Util.stringMd5(airshowDistributorLoginReq.getPwd()));

        AirshowDistributorSetting airshowDistributorSetting = airshowDistributorSettingMapper.selectOne(queryWrapper);

        if(airshowDistributorSetting == null){
            throw new BusinessException(SystemError.SYS_433,"账号或密码错误");
        }

//        AirshowDistributorSettingDTO airshowDistributorSettingDTO = new AirshowDistributorSettingDTO();
//        airshowDistributorSettingDTO.setId(airshowDistributorSetting.getId());
//        airshowDistributorSettingDTO.setAgentName(airshowDistributorSetting.getAgentName());

        TokenUser tokenUser = new TokenUser();
        tokenUser.setId(airshowDistributorSetting.getId());
        tokenUser.setUsername(airshowDistributorSetting.getAgentName());

        String token = RSAUtil.encryptStr(JSONObject.toJSONString(tokenUser));
        String tokenKey = RedisConstants.TOKEN_USER_KEY + airshowDistributorSetting.getId();

        redisTemplate.opsForValue().set(tokenKey,token,8, TimeUnit.HOURS);

        return Result.success(token);
    }

    @Override
    public Integer surplusDistributorBalance(Long id, BigDecimal amount) {

        Integer integer = airshowDistributorSettingMapper.surplusBalance(id, amount);

        return integer;
    }

    @Override
    public Integer addDistributorBalance(Long id, BigDecimal amount) {

        Integer integer = airshowDistributorSettingMapper.addBalance(id, amount);

        return integer;
    }

    @Override
    public TokenUser getAPIToken(String token) {
//        String token = request.getHeader("appkey");
        if (org.apache.commons.lang3.StringUtils.isBlank(token)) {
            throw new BusinessException(SystemError.USER_1028);
        }
        TokenUser tokenUser = new TokenUser();

        QueryWrapper<AirshowDistributorSetting> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("app_secret",token);
        queryWrapper.eq("is_enable",1);
        queryWrapper.eq("is_delete",0);

        AirshowDistributorSetting airshowDistributorSetting = airshowDistributorSettingMapper.selectOne(queryWrapper);

        if(airshowDistributorSetting == null){
            throw new BusinessException(SystemError.USER_1002);
        }

        tokenUser.setId(airshowDistributorSetting.getId());
        tokenUser.setUsername(airshowDistributorSetting.getAgentName());

        return tokenUser;
    }

}
